const app = getApp()
const util = require('../../../../../utils/util.js');
const api = require('../../../../../config/api.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;
Page({
  data: {
    // 判断是创建还是跟新，如果是创建的，没关闭当前页面，就是一直处于创建
    o_type: "",
    platform: '',//获取客户端
    scoreList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],//设置分数用的
    // 主题基本信息
    ordTheme: { "id": "", "type": "", "title": "", "circleid": "", "openid": "", "firstImageIp": "", "firstImageUrl": "", "contentType": 1, "isAppreciate": 0, "themeTime": "", "themeCheckpoint": "", "recommendDesc": "" },
    // 主题基本信息辅助的对象
    ordThemeAuxiliary: { "themeTimeStart": "", "themeTime": "", "titleInput": false, "firstImagePopupShow": false, "contentTypePopupShow": false, "recommendDescFocus": false, "showOccupied": false, "themeNotSelectTime": [], "amountDesc": "" },
    // 主题推荐信息
    ordThemeRecommendList: [],
    // 主题推荐信息辅助对象
    ordThemeRecommendListAuxiliary: { "baobeiList": [], "circleList": [] },
    // 视频、音频、图片、文字、链接、位置、单选、多选、判断、问答、评星、填空信息
    dataInfoList: [],
    // 视频、音频、图片、文字、链接、位置、单选、多选、判断、问答、评星、填空信息的辅助对象
    dataInfoListAuxiliary: { "imagePopupShow": false, "isOpenDiaShow": false, "videoPopupShow": false, "audioOauhRefusedDialogShow": false, "linkPopupShow": false, "isRecorderStart": false, "videoPopupShow": false, "linkErrorDialogShow": false, "linkNameDialogShow": false, "voiceDialogShow": false, "voiceUpdateIndex": "", "voiceUpdateTitle": "", "nickName": "", "albumInfoDeleteIndex": "", "voiceDialogDeleteShow": "", "recommendPopupShow": "" },
    themeJoinCount: 0,// 主题加入人数
    themeAnswerCount: 0,// 主题参与人数
    themeSetting: {},// 问卷设置
    themeAmount: {},// 收益明细
    themeAmountDetailsList: [],// 多个收益明细详情
  },
  onLoad: function (options) {
    var _this = this;
    var themeid = options.themeid;
    var circleid = options.circleid;
    var type = options.type;
    var nickName = app.globalData.logininfo.userInfo.nickName;
    _this.setData({
      ["ordTheme.id"]: themeid == null ? "" : themeid,
      ["ordTheme.circleid"]: circleid,
      ["ordTheme.type"]: type,
      ["dataInfoListAuxiliary.nickName"]: nickName,
      o_type: options.o_type == null || String(options.o_type).length <= 0 ? "update" : options.o_type
    })
    if (type == 1) {
      _this.getThemeAndGroupNotSelectTime();
    }
    var platform = wx.getSystemInfoSync().platform;
    _this.setData({
      platform: platform
    })
    if (themeid == null || String(themeid).length <= 0) {
      // 没有主题
      if (type == 1) {
        // 经典模式，限制选择日期的开始时间
        _this.setData({
          ["ordThemeAuxiliary.themeTimeStart"]: util.getDateStr(new Date(), 0)
        })
        // 获取推荐信息
        _this.loadRecommendedCircles();
      } else if (type == 2) {
        // 闯关模式，从数据库获取第几关
        _this.getThemeInfoByUpdate();
      }
    } else {
      // 有主题，是修改，需要从数据库获取主题信息
      _this.getThemeInfoByUpdate();
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    var themeid = _this.data.ordTheme.id;
    if (themeid == null || String(themeid).length <= 0) {
      _this.getTicketPrice(_this.data.themeAmountDetailsList);
    }else{
      _this.getTicketPrice2();
    }
    
  },
  /**
  * 查询不可选的日期（过滤主题和主题组）
  */
  getThemeAndGroupNotSelectTime: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.ordTheme.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeAndGroupNotSelectTimeApi, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              ["ordThemeAuxiliary.themeNotSelectTime"]: res.result
            })
          }
        })
      })
    }
  },
  /**
   * 获取圈子详情
   */
  getThemeInfoByUpdate: function () {
    var _this = this;
    var circleid = _this.data.ordTheme.circleid;
    var themeid = _this.data.ordTheme.id;
    var type = _this.data.ordTheme.type;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = circleid;
        data.themeid = themeid;
        data.type = type
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeInfoByUpdateApi, data).then(res => {
          if (res.code == 200) {
            if (themeid == null || String(themeid).length <= 0 && type == 2) {
              // 获取关卡
              _this.setData({
                ["ordTheme.themeCheckpoint"]: res.result.ordTheme.themeCheckpoint
              })
            } else {
              // 获取主题信息
              var ordTheme = res.result.ordTheme;
              var dataInfoList = res.result.dataInfoList;
              var ordThemeRecommendList = res.result.ordThemeRecommendList;
              var themeJoinCount = res.result.themeJoinCount;
              var themeAnswerCount = res.result.themeAnswerCount;
              var themeTime = ordTheme.themeTime;
              var maxCheckpoint = res.result.maxCheckpoint;
              var ordThemeAmount = res.result.ordThemeAmount;
              var ordThemeAmountDetailsList = res.result.ordThemeAmountDetailsList;
              var themeTime2 = "";
              if (themeTime != null && themeTime.length > 0) {
                themeTime2 = themeTime.replace("-", "年").replace("-", "月") + "日";
              }
              for (var i = 0; i < dataInfoList.length; i++) {
                var dataInfo = dataInfoList[i];
                switch (dataInfo.type) {
                  case 1:
                    dataInfo.focus = false;
                    dataInfo.autoheight = false;
                    break;
                  case 3:
                    dataInfo.startDate = "00:00";
                    dataInfo.state = 2;
                    dataInfo.voiceBoFangImage = api.AudioNoBoFangImage_Name;
                    dataInfo.currentTime = 0;
                    break;
                  case 4:
                    var videoid = "myVideo" + new Date().getTime() + i;
                    dataInfo.videoid = videoid;
                    break;
                  case 5:
                    dataInfo.state = 2;
                    dataInfo.textareaPlaceholderShow = false;
                    break;
                }
                dataInfoList[i] = dataInfo;
              }
              _this.setData({
                ordTheme: ordTheme,
                themeJoinCount: themeJoinCount,
                themeAnswerCount: themeAnswerCount,
                dataInfoList: dataInfoList,
                ordThemeRecommendList: ordThemeRecommendList,
                themeAmount: ordThemeAmount,
                themeAmountDetailsList: ordThemeAmountDetailsList,
                ["ordThemeAuxiliary.themeTime"]: themeTime2,
              })
              var o_type = _this.data.o_type;
              if (o_type == "copy") {
                _this.setData({
                  ["ordTheme.id"]: ""
                })
                if(type == 1){
                  _this.setData({
                    ["ordTheme.themeTime"]: "",
                    ["ordThemeAuxiliary.themeTime"]: ""
                  })
                }else if(type == 2){
                  _this.setData({
                    ["ordTheme.themeCheckpoint"]: maxCheckpoint + 1,
                  })
                }
              }
            }
            // 获取推荐信息
            _this.loadRecommendedCircles();
          }
        })
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  /**
   * 主题标题鼠标移入事件
   */
  themeTitleTap: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.titleInput"]: true
    })
  },
  /**
   * 主题标题鼠标移出事件
   */
  themeTitleBlur: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.titleInput"]: false
    })
  },
  /**
   * 主题标题输入事件
   */
  themeTitleInput: function (e) {
    var _this = this
    var value = e.detail.value.replace(/\s+/g, '')
    _this.setData({
      ["ordTheme.title"]: value,
    })
  },
  /**
   * 主题日期选择
   */
  themeTimeChange: function (e) {
    var _this = this;
    var themeTime = e.detail.value;
    var themeNotSelectTime = _this.data.ordThemeAuxiliary.themeNotSelectTime;
    for (var i = 0; i < themeNotSelectTime.length; i++) {
      if (themeNotSelectTime[i] == themeTime) {
        util.showToast("不能选择" + themeTime, "none");
        return;
      }
    }
    var themeTime2 = themeTime.replace("-", "年").replace("-", "月") + "日";
    _this.setData({
      ["ordTheme.themeTime"]: themeTime,
      ["ordThemeAuxiliary.themeTime"]: themeTime2,
    })
  },
  /**
   * 打开选择上传头图的选择器
   */
  firstImagePopupShow: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.firstImagePopupShow"]: true,
    })
  },

  /**
   * 关闭选择上传头图的选择器
   */
  firstImagePopupClose: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.firstImagePopupShow"]: false,
    })
  },

  /**
   * 选择头图：拍照
   */
  firstImageToTakingPictures: function () {
    var _this = this
    var imgArr = []
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success(res) {
        _this.setData({
          ["ordThemeAuxiliary.firstImagePopupShow"]: false,
        })
        wx.navigateTo({
          url: '/ucenter/pages/background/upload/index?type=themePoster&imageSrc=' + res.tempFilePaths[0],
        })
      }
    })
  },
  /**
   * 选择头图：相册
   */
  firstImageToPhotoAlbum: function () {
    var _this = this
    var imgArr = []
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success(res) {
        _this.setData({
          ["ordThemeAuxiliary.firstImagePopupShow"]: false,
        })
        wx.navigateTo({
          url: '/ucenter/pages/background/upload/index?type=themePoster&imageSrc=' + res.tempFilePaths[0],
        })
      }
    })
  },

  /**
   * 选择头图：从微信中导入图片
   */
  firstImageToWeChat: function () {
    var _this = this
    var imgArr = []
    wx.chooseMessageFile({
      count: 1,
      type: 'image',
      success(res) {
        _this.setData({
          ["ordThemeAuxiliary.firstImagePopupShow"]: false,
        })
        wx.navigateTo({
          url: '/ucenter/pages/background/upload/index?type=themePoster&imageSrc=' + res.tempFiles[0].path,
        })
      }
    })
  },
  /**
   * 删除头图
   */
  delFirstImage: function () {
    var _this = this
    _this.setData({
      ["ordTheme.firstImageIp"]: "",
      ["ordTheme.firstImageUrl"]: "",
    })
  },
  /**
   * 打开主题内容类型说明
   */
  contentTypePopupShow: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.contentTypePopupShow"]: true,
    })
  },
  /**
   * 关闭主题内容类型说明
   */
  contentTypePopupClose: function () {
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.contentTypePopupShow"]: false,
    })
  },
  /**
   * 进入选择内容类型
   */
  navigateToContentType: function () {
    var _this = this
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    wx.navigateTo({
      url: 'contentType/contentType?type=' + contentType,
    })
  },

  /**
   * 详情设置
   */
  addDataInfo: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var type = String(e.currentTarget.dataset.type);
    var dataInfoList = _this.data.dataInfoList;
    switch (type) {
      case "1":
        // 文字
        var info = {};
        info.type = type;
        info.focus = true;
        info.autoheight = true;
        info.value = "";
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        break;
      case "2":
        // 图片
        _this.setData({
          ["dataInfoListAuxiliary.imagePopupShow"]: true,
          ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        })
        break;
      case "3":
        // 音频
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.record']) {
              // 未授权
              wx.authorize({
                scope: 'scope.record',
                success() {
                  _this.recorderStart(dataInfoList, dataInfoList.length, type);
                },
                fail: function () {
                  // 拒绝授权
                  _this.setData({
                    ["dataInfoListAuxiliary.audioOauhRefusedDialogShow"]: true,
                    ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
                  })
                }
              })
            } else {
              // 已授权
              _this.recorderStart(dataInfoList, dataInfoList.length, type);
            }
          }
        })
        break;
      case "4":
        // 视频
        _this.setData({
          ["dataInfoListAuxiliary.videoPopupShow"]: true,
          ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        })
        break;
      case "5":
        // 链接
        _this.setData({
          ["dataInfoListAuxiliary.linkPopupShow"]: true,
          ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        })
        break;
      case "6":
        // 位置
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              // 未授权
              wx.authorize({
                scope: 'scope.userLocation',
                success() {
                  _this.dataInfoPositionStart(dataInfoList, type);
                },
                fail: function () {
                  // 拒绝授权
                  _this.setData({
                    ["dataInfoListAuxiliary.addressOauhRefusedDialogShow"]: true,
                    ["dataInfoListAuxiliary.isOpenDiaShow"]: true,

                  })
                }
              })
            } else {
              // 已授权
              _this.dataInfoPositionStart(dataInfoList, type);
            }
          }
        })
        break;
      case "-1":
        // 赞赏
        _this.setData({
          ["ordTheme.isAppreciate"]: 1
        })
        break;
      case "-2":
        // 推荐
        _this.recommendPopupShow();
        break;
      case "7":
        // 单选
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.optionFormList = [];
        if (contentType == 3) {
          info.answerFormList = [];
          info.score = 5;
        }
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1, 9);
        _this.addOptionQuery(dataInfoList.length - 1);
        break;
      case "8":
        // 多选
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.optionFormList = [];
        if (contentType == 3) {
          info.answerFormList = [];
          info.score = 5;
        }
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1, 9);
        _this.addOptionQuery(dataInfoList.length - 1);
        break;
      case "9":
        // 判断
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.optionFormList = [];
        info.answerFormList = [];
        info.score = 5;
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1, type);
        _this.addOptionQuery(dataInfoList.length - 1, type);
        break;
      case "10":
        // 问答
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.answer = '';
        info.optionFormList = [];
        info.answerFormList = [];
        info.score = 5;
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1);
        break;
        break;
      case "11":
        // 评星
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.optionFormList = [];
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1);
        break;
      case "12":
        // 填空
        var info = {};
        info.type = type;
        info.serial = '';
        info.title = '';
        info.optionFormList = [];
        if (contentType == 3) {
          info.answerFormList = [];
          info.score = 5;
        }
        dataInfoList.push(info);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
        _this.addOptionQuery(dataInfoList.length - 1);
        _this.addOptionQuery(dataInfoList.length - 1);
        break;
    }
    _this.setSerial();
  },
  /**
   * 兴趣专辑详情上移
   */
  albumLast: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var index = e.currentTarget.dataset.index;
    if (index == 0) {
      // 第一个元素不能往前移动
      return false;
    }
    var isRecorderStart = _this.data.dataInfoListAuxiliary.isRecorderStart;
    if (isRecorderStart) {
      // 录音中，不能上移
      return false;
    }
    var dataInfoList = _this.data.dataInfoList;
    dataInfoList.splice(index - 1, 0, dataInfoList[index]);
    dataInfoList.splice(index + 1, 1);
    _this.setData({
      ["dataInfoList"]: dataInfoList
    })
    _this.setSerial();
  },
  /**
     * 兴趣专辑详情下移
     */
  albumNext: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var dataInfoList = _this.data.dataInfoList;
    var index = e.currentTarget.dataset.index;
    if (index + 1 == dataInfoList.length) {
      // 第一个元素不能往后移动
      return false;
    }
    var isRecorderStart = _this.data.dataInfoListAuxiliary.isRecorderStart;
    if (isRecorderStart) {
      // 录音中，不能下移
      return false;
    }
    dataInfoList.splice(index + 2, 0, dataInfoList[index]);
    dataInfoList.splice(index, 1);
    _this.setData({
      ["dataInfoList"]: dataInfoList
    })
    _this.setSerial();
  },
  /**
   * 兴趣专辑详情删除:弹出dialog
   */
  albumDeleteDialogShow: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    // 测评和统计的，在创建之后不能修改
    var albumInfoDeleteIndex = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoListAuxiliary.albumInfoDeleteIndex"]: albumInfoDeleteIndex,
      ["dataInfoListAuxiliary.voiceDialogDeleteShow"]: true,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
    })
  },
  /**
 * 兴趣专辑详情关闭dialog
 */
  albumDeleteDialogClose: function (e) {
    var _this = this;
    if (e.detail == "confirm") {
      var albumInfoDeleteIndex = _this.data.dataInfoListAuxiliary.albumInfoDeleteIndex;
      if (albumInfoDeleteIndex == "-1") {
        _this.setData({
          ["ordTheme.isAppreciate"]: 0,
        })
      } else if (albumInfoDeleteIndex == "-2") {
        _this.setData({
          ["ordThemeRecommendList"]: [],
        })
      } else {
        var dataInfoList = _this.data.dataInfoList;
        var type = dataInfoList[albumInfoDeleteIndex].type;
        var state = dataInfoList[albumInfoDeleteIndex].state;
        if (type == "3" && state == "1") {
          // 删除录音：因为录音会触发录音动作，需要先删除录音动作再进行删除view
          _this.setData({
            ["dataInfoList[" + albumInfoDeleteIndex + "].isVoiceDialogShow"]: false
          })
          _this.doClearInterval();
          recorderManager.stop();
        }
        dataInfoList.splice(albumInfoDeleteIndex, 1);
        _this.setData({
          ["dataInfoList"]: dataInfoList
        })
      }
    }
    _this.setData({
      ["dataInfoListAuxiliary.albumInfoDeleteIndex"]: "",
      ["dataInfoListAuxiliary.voiceDialogDeleteShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
    _this.setSerial();
  },
  /**
  * 编辑详情文字的焦点移出事件
  */
  albumInfoTextareaBlur: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var isSwitchEmoji = false;
    if (e.detail != null && e.detail.isSwitchEmoji != null) {
      isSwitchEmoji = e.detail.isSwitchEmoji;
    }
    if (!isSwitchEmoji) {
      _this.setData({
        ["dataInfoList[" + index + "].focus"]: false,
        ["dataInfoList[" + index + "].autoheight"]: false
      })
    }
  },
  /**
  * 编辑详情文字的焦点移出事件
  */
  albumInfoTextareaInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].value"]: value
    })
  },
  /**
   * 编辑详情文字的聚焦事件
   */
  albumInfoTextareaFocus: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].focus"]: true,
      ["dataInfoList[" + index + "].autoheight"]: true
    })
  },
  /**
   * 图片弹出层选择
   */
  imageSelect: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var dataInfoList = _this.data.dataInfoList;
    if (type == 1) {
      // 拍照
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['camera'],
        success(res) {
          for (var i = 0; i < res.tempFiles.length; i++) {
            var info = {};
            info.type = 2;
            var themeImageList = [];
            var themeImage = {};
            themeImage.ip = "";
            themeImage.path = res.tempFiles[i].path;
            themeImageList.push(themeImage);
            info.themeImageList = themeImageList;
            dataInfoList.push(info);
          }
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.imagePopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          })
        }
      })
    } else if (type == 2) {
      // 从手机相册选择
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success(res) {
          for (var i = 0; i < res.tempFiles.length; i++) {
            var info = {};
            info.type = 2;
            var themeImageList = [];
            var themeImage = {};
            themeImage.ip = "";
            themeImage.path = res.tempFiles[i].path;
            themeImageList.push(themeImage);
            info.themeImageList = themeImageList;
            dataInfoList.push(info);
          }
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.imagePopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          })
        }
      })
    } else if (type == 3) {
      //从微信导入图片
      wx.chooseMessageFile({
        count: 9,
        type: 'image',
        success(res) {
          for (var i = 0; i < res.tempFiles.length; i++) {
            var info = {};
            info.type = 2;
            var themeImageList = [];
            var themeImage = {};
            themeImage.ip = "";
            themeImage.path = res.tempFiles[i].path;
            themeImageList.push(themeImage);
            info.themeImageList = themeImageList;
            dataInfoList.push(info);
          }
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.imagePopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          })
        }
      })
    }
  },
  /**
    * 预览图片
    */
  previewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var dataInfoList = _this.data.dataInfoList;
    var urls = [];
    var current = dataInfoList[index].themeImageList[yindex].ip + dataInfoList[index].themeImageList[yindex].path;
    urls.push(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  /**
     * 关闭图片弹出层
     */
  imagePopupClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.imagePopupShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },
  /**
   * 开始录音
   */
  recorderStart: function (dataInfoList, dataInfoLength, type) {
    var _this = this;
    var isPlay = true;//是否可以录音
    for (var i = 0; i < dataInfoList.length; i++) {
      if (dataInfoList[i].type == type) {
        if (dataInfoList[i].state == "1") {
          isPlay = false;
          break;
        }
      }
    }
    if (isPlay) {
      var info = {};
      info.type = type;
      info.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
      info.playState = "1";// 1正常录音  2暂停录音
      info.totalTime = 0;
      info.totalDate = "00:00";
      info.isVoiceDialogShow = true;
      info.title = "";
      dataInfoList.push(info);
      _this.setData({
        ["dataInfoList"]: dataInfoList,
        ["dataInfoListAuxiliary.isRecorderStart"]: true
      })

      const recorderOptions = {
        duration: util.getAudioFileMaxTime("theme"),
        format: 'mp3'
      }
      //开始录音
      recorderManager.start(recorderOptions);

      // 定时器计算录音时间
      _this.doRecordInterval(dataInfoLength);

      // 录音结束
      recorderManager.onStop((res) => {
        _this.stopRecorderExecute(dataInfoLength, res);
      });

      // 录音中断
      recorderManager.onInterruptionBegin((res) => {
        recorderManager.stop();
        _this.setData({
          ["dataInfoList[" + dataInfoLength + "].isVoiceDialogShow"]: false
        })
        _this.stopRecorderExecute(dataInfoLength, res);
      });
    }
  },

  /**
   * 开始录音
   */
  recorderStart2: function (index) {
    var _this = this;
    var info = {};
    info.type = 3;
    info.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    info.playState = "1";// 1正常录音  2暂停录音
    info.totalTime = 0;
    info.totalDate = "00:00";
    info.isVoiceDialogShow = true;
    _this.setData({
      ["dataInfoList[" + index + "]"]: info,
      ["dataInfoListAuxiliary.isRecorderStart"]: true
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("theme"),
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doRecordInterval(index);

    // 录音结束
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(index, res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.setData({
        ["dataInfoList[" + index + "].isVoiceDialogShow"]: false
      })
      _this.stopRecorderExecute(index, res);
    });

  },

  /**
   * 定时器计算录音时间
   */
  doRecordInterval: function (index) {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var dataInfo = _this.data.dataInfoList[index];
        var totalTime = dataInfo.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["dataInfoList[" + index + "].totalTime"]: totalTime,
          ["dataInfoList[" + index + "].totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 停止录音后的业务代码
   */
  stopRecorderExecute: function (index, tempFile) {
    var _this = this;
    _this.doClearInterval();
    var dataInfo = _this.data.dataInfoList[index];
    if (dataInfo != null) {
      var isVoiceDialogShow = dataInfo.isVoiceDialogShow;
      if (isVoiceDialogShow) {
        var totalTime = parseInt(tempFile.duration / 1000);
        dataInfo.state = "2";
        dataInfo.ip = "";
        dataInfo.path = tempFile.tempFilePath;
        dataInfo.title = "";
        dataInfo.currentTime = 0;
        dataInfo.totalTime = totalTime;
        dataInfo.fileSize = tempFile.fileSize;
        dataInfo.startDate = "00:00";
        dataInfo.totalDate = util.digitalFormatTime(totalTime);
        dataInfo.voiceBoFangImage = api.AudioNoBoFangImage_Name;
        _this.setData({
          ["dataInfoList[" + index + "]"]: dataInfo,
        })
        _this.voiceDialogShow(index);
      }
    }
    _this.setData({
      ["dataInfoListAuxiliary.isRecorderStart"]: false
    })
  },

  /**
   * 清除定时器
   */
  doClearInterval: function () {
    clearInterval(recordInterval);
    recordInterval = null;
  },

  /**
   * 是否展示音频dialog
   */
  voiceDialogShow: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var voiceDialogShow = _this.data.dataInfoListAuxiliary.voiceDialogShow;
    var index = e.currentTarget == null ? e : e.currentTarget.dataset.index;
    var title = _this.data.dataInfoList[index].title;
    if (voiceDialogShow) {
      // 关闭
      if (title != null && title.trim().length <= 0) {
        title = _this.data.dataInfoListAuxiliary.nickName + "的音频";
      }
      _this.setData({
        ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
        ["dataInfoListAuxiliary.voiceDialogShow"]: false,
        ["dataInfoListAuxiliary.voiceUpdateIndex"]: "",
        ["dataInfoList[" + index + "].title"]: title,
        ["dataInfoListAuxiliary.voiceUpdateTitle"]: ""
      })
    } else {
      // 开启
      _this.setData({
        ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        ["dataInfoListAuxiliary.voiceDialogShow"]: true,
        ["dataInfoListAuxiliary.voiceUpdateIndex"]: index,
        ["dataInfoListAuxiliary.voiceUpdateTitle"]: title
      })
    }
  },

  /**
   * 停止录音
   */
  stopRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(index, res);
    });
  },

  /**
   * 录音音频名称的修改
   */
  voiceUpdateTitle: function (e) {
    var _this = this;
    var title = e.detail;
    var index = _this.data.dataInfoListAuxiliary.voiceUpdateIndex;
    if (title.trim().length <= 0) {
      title = _this.data.dataInfoListAuxiliary.nickName + "的录音音频";
    }
    _this.setData({
      ["dataInfoList[" + index + "].title"]: title
    })
  },

  /**
   * 清空录音
   */
  clearRecorder: function (e) {
    var _this = this;
    var dataInfoList = _this.data.dataInfoList;
    var dataInfoLength = dataInfoList.length;
    var index = e.currentTarget.dataset.index;
    _this.doClearInterval();
    _this.setData({
      ["dataInfoList[" + index + "].isVoiceDialogShow"]: false
    })
    recorderManager.stop();

    setTimeout(function () {
      // 音频
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.record']) {
            // 未授权
            wx.authorize({
              scope: 'scope.record',
              success() {
                _this.recorderStart2(index);
              },
              fail: function () {
                // 拒绝授权
                _this.setData({
                  ["dataInfoListAuxiliary.audioOauhRefusedDialogShow"]: true
                })
              }
            })
          } else {
            // 已授权
            _this.recorderStart2(index);
          }
        }
      })
    }, 100)
  },

  /**
   * 暂停录音
   */
  pauseRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音
   */
  resumeRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].playState"]: "1"
    })
    recorderManager.resume();
    _this.doRecordInterval(index);
  },

  /**
   * 播放或暂停动作
   */
  voiceBoFang: function (e) {
    var _this = this;
    var path = e.currentTarget.dataset.path;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = path;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["dataInfoList[" + index + "].currentTime"]: 0,
          ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name,
          ["dataInfoList[" + index + "].startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["dataInfoList[" + index + "].currentTime"]: backgroundAudioManager.currentTime,
          ["dataInfoList[" + index + "].startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioBoFangImage_Name
      });
    }
  },

  /**
   * 播放音乐（滚动条事件）
   */
  voiceSlider: function (e) {
    var _this = this;
    var position = e.detail.value;
    var path = e.currentTarget.dataset.path;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var voiceStartDate = util.digitalFormatTime(position);
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      //正在播放状态：不知道为什么，录音的在调用backgroundAudioManager.seek(Math.floor(position))方法无效，所以改成一下这种方式
      e.currentTarget.dataset.currenttime = position;
      e.currentTarget.dataset.voiceimage = api.AudioNoBoFangImage_Name;
      _this.voiceBoFang(e);
    } else {
      // 未播放状态
      _this.setData({
        ["dataInfoList[" + index + "].currentTime"]: position,
        ["dataInfoList[" + index + "].startDate"]: voiceStartDate
      });
    }
  },
  /**
     * 视频弹出层选择
     */
  videoSelect: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var dataInfoList = _this.data.dataInfoList;
    if (type == 1) {
      // 拍摄
      wx.chooseVideo({
        sourceType: ['camera'],
        maxDuration: util.getVideoFileMaxTime("theme"),
        camera: 'back',
        success(res) {
          var size = res.size;
          var width = res.width;
          var height = res.height;
          var duration = parseInt(res.duration);
          var tempFilePath = res.tempFilePath;
          var videoid = "myVideo" + new Date().getTime();
          var totalDate = util.digitalFormatTime(duration);
          var info = {};
          info.videoid = videoid;
          info.size = size;
          info.width = width;
          info.height = height;
          info.type = 4;
          info.ip = "";
          info.path = tempFilePath;
          info.totalTime = duration;
          info.totalDate = totalDate;
          dataInfoList.push(info);
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.videoPopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          })
        }
      })
    } else if (type == 2) {
      // 从手机相册选择
      wx.chooseVideo({
        sourceType: ['album'],
        maxDuration: util.getVideoFileMaxTime("theme"),
        camera: 'back',
        success(res) {
          var size = res.size;
          var maxSize = util.getVideoFileMaxSize("theme");
          if ((size / 1024 / 1024) > maxSize) {
            util.dialogAlert("视频大小超出" + maxSize + "M");
            return;
          }

          var width = res.width;
          var height = res.height;
          var duration = parseInt(res.duration);
          var tempFilePath = res.tempFilePath;
          var videoid = "myVideo" + new Date().getTime();
          var totalDate = util.digitalFormatTime(duration);
          var info = {};
          info.videoid = videoid;
          info.size = size;
          info.width = width;
          info.height = height;
          info.type = 4;
          info.ip = "";
          info.path = tempFilePath;
          info.totalTime = duration;
          info.totalDate = totalDate;
          dataInfoList.push(info);
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.videoPopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          })
        }
      })
    } else if (type == 3) {
      //从微信导入视频
      wx.chooseMessageFile({
        count: 1,
        type: 'video',
        success(res) {
          var tempFiles = res.tempFiles[0];
          var size = tempFiles.size;
          var maxSize = util.getVideoFileMaxSize("theme");
          if ((size / 1024 / 1024) > maxSize) {
            util.dialogAlert("视频大小超出" + maxSize + "M");
            return;
          }

          var tempFilePath = tempFiles.path;
          var videoid = "myVideo" + new Date().getTime();
          var info = {};
          info.videoid = videoid;
          info.size = size;
          info.width = 0;
          info.height = 0;
          info.totalTime = 0;
          info.totalDate = "";
          info.type = 4;
          info.ip = "";
          info.path = tempFilePath;
          dataInfoList.push(info);
          _this.setData({
            ["dataInfoList"]: dataInfoList,
            ["dataInfoListAuxiliary.videoPopupShow"]: false,
            ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
          });
        }
      })
    }
  },

  /**
   * 关闭视频弹出层
   */
  videoPopupClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.videoPopupShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },

  /**
   * 视频播放
   */
  videoPlay: function (e) {
    var _this = this;
    var videoid = e.currentTarget.dataset.videoid;
    this.videoContext = wx.createVideoContext(videoid);
    this.videoContext.pause();
  },

  /**
   * 跳转到视频播放页面
   */
  toVideo: function (e) {
    var _this = this;
    var path = e.currentTarget.dataset.path;
    wx.navigateTo({
      url: '/pages/home/video/video?state=0&type=1&id=&src=' + path,
    })
  },
  /**
     * 链接底部弹出的选择
     */
  linkSelect: function (e) {
    var _this = this;
    var dataInfoList = _this.data.dataInfoList;
    _this.linkPopupClose();
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      // 粘贴公众号文章链接
      var info = {};
      info.type = 5;
      info.linkType = 1;
      info.title = "";
      info.ip = "";
      info.value = "";
      info.focus = true;
      info.textareaPlaceholderShow = true;
      info.state = "1";
      dataInfoList.push(info);
      _this.setData({
        ["dataInfoList"]: dataInfoList
      })
    } else if (type == 2) {
      // 从微信导入文件
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          var tempFile = res.tempFiles[0];
          var path = tempFile.path;
          var pathIndex1 = path.lastIndexOf(".");
          var pathIndex2 = path.length;
          var suffix = path.substring(pathIndex1 + 1, pathIndex2);//后缀名
          var fileLegalSuffix = util.fileLegalSuffix();
          if (fileLegalSuffix.indexOf(suffix) > -1) {
            var info = {};
            info.type = 5;
            info.linkType = 2;
            info.title = tempFile.name;
            info.ip = "";
            info.value = tempFile.path;
            info.size = tempFile.size;
            info.state = "2";
            dataInfoList.push(info);
            _this.setData({
              ["dataInfoList"]: dataInfoList
            })
          } else {
            util.dialogAlert("请选择" + String(fileLegalSuffix) + "格式的文件");
          }
        }
      })
    }
  },

  /**
   * 关闭链接错误提示
   */
  linkErrorDialogClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.linkErrorDialogShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },

  /**
  * 跳转到链接展示页面：日记
  */
  navigateToWebView: function (e) {
    var text = e.currentTarget.dataset.text;
    var linkType = e.currentTarget.dataset.linktype;
    if (linkType == 1) {
      wx.navigateTo({
        url: '/pages/home/webView/webView?src=' + text,
      })
    } else {
      wx.openDocument({
        filePath: text,
        success: function (res) {
        }
      })
    }
  },

  /**
   * 链接的焦点移出事件
   */
  albumInfoHrefInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].title"]: "",
      ["dataInfoList[" + index + "].value"]: value,
      ["dataInfoList[" + index + "].textareaPlaceholderShow"]: false
    })
    if (value.length <= 0) {
      _this.setData({
        ["dataInfoList[" + index + "].textareaPlaceholderShow"]: true
      })
    }
  },

  /**
   * 链接的焦点移出事件
   */
  albumInfoHrefBlur: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var value = _this.data.dataInfoList[index].value;
    _this.setData({
      ["dataInfoList[" + index + "].focus"]: false
    })
    if (_this.checkLink(index) && value.length > 0) {
      _this.setData({
        ["dataInfoListAuxiliary.linkNameDialogShow"]: true,
        ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        ["dataInfo.linkAlbumInfoIndex"]: index
      })
    }
  },

  /**
   * 公众号名称编辑事件
   */
  linkNameInput: function (e) {
    var _this = this;
    var name = e.detail.value;
    var index = _this.data.dataInfo.linkAlbumInfoIndex;
    _this.setData({
      ["dataInfoList[" + index + "].title"]: name
    })
  },

  /**
   * 公众号名称弹窗关闭事件
   */
  linkNameDialogClose: function (e) {
    var _this = this;
    var index = _this.data.dataInfo.linkAlbumInfoIndex;
    var title = _this.data.dataInfoList[index].title;
    if (title.length <= 0) {
      _this.setData({
        ["dataInfoList[" + index + "].title"]: "公众号文章"
      })
    }
    _this.setData({
      ["dataInfoListAuxiliary.linkNameDialogShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
      ["dataInfo.linkAlbumInfoIndex"]: "",
      ["dataInfoList[" + index + "].state"]: "2"
    })
  },

  /**
   * 校验链接
   */
  checkLink: function (index) {
    var _this = this;
    var dataInfo = _this.data.dataInfoList[index];
    var linkType = dataInfo.linkType;
    if (linkType == 1) {
      var value = dataInfo.value.trim();
      var reg = /^https:\/\/mp.weixin.qq.com*/;
      if (value.length > 0 && !reg.test(value)) {
        _this.setData({
          ["dataInfoListAuxiliary.linkErrorDialogShow"]: true,
          ["dataInfoListAuxiliary.isOpenDiaShow"]: true,
        })
        return false;
      }
    }
    return true;
  },

  /**
   * 关闭链接的底部弹窗
   */
  linkPopupClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.linkPopupShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },
  /**
     * 位置
     */
  dataInfoPositionStart: function (dataInfoList, type) {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var value = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (value != null && value.length > 0) {
          var info = {};
          info.type = type;
          info.value = value;
          info.latitude = latitude;
          info.longitude = longitude;
          info.address = address;
          dataInfoList.push(info);
          _this.setData({
            ["dataInfoList"]: dataInfoList
          })
        } else {
          util.dialogAlert("未选中有效地址")
        }
      }
    })
  },
  /**
   * 是否显示推荐圈子的popup
   */
  recommendPopupShow: function () {
    var _this = this;
    var recommendPopupShow = _this.data.dataInfoListAuxiliary.recommendPopupShow;
    _this.setData({
      ["dataInfoListAuxiliary.recommendPopupShow"]: !recommendPopupShow,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: !recommendPopupShow,
    })
  },
  /**
   * 推荐项目确认动作
   */
  recommendConfirm: function () {
    var _this = this;
    var ordThemeRecommendList = [];
    var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
    var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
    for (var i = 0; i < circleList.length; i++) {
      if (circleList[i].circlesChecked) {
        var valueInfo = {};
        valueInfo.recommendId = circleList[i].id;
        valueInfo.title = circleList[i].title;
        valueInfo.peopleNumber = circleList[i].renshu;
        valueInfo.clockNumber = circleList[i].qiandao;
        valueInfo.money = circleList[i].showCirclesMoney;
        valueInfo.image = circleList[i].beijing;
        valueInfo.isCommission = circleList[i].isCommission;
        valueInfo.recommendType = "1";//1圈子  2宝贝
        ordThemeRecommendList.push(valueInfo);
      }
    }
    for (var i = 0; i < baobeiList.length; i++) {
      if (baobeiList[i].circlesChecked) {

      }
    }
    _this.setData({
      ["ordThemeRecommendList"]: ordThemeRecommendList
    })
    _this.recommendPopupShow();
  },

  /**
   * 推荐的tabs切换
   */
  recommendTabsChange: function (event) {
    var _this = this;
    var index = event.detail.index;
    _this.setData({
      ["tabs.tabsActive"]: index
    })
  },

  /**
   * 推荐信息选中事件
   */
  recommendClick: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
    var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
    var count = 0;
    for (var i = 0; i < circleList.length; i++) {
      if (circleList[i].circlesChecked) {
        count = count + 1;
      }
    }
    for (var i = 0; i < baobeiList.length; i++) {
      if (baobeiList[i].circlesChecked) {
        count = count + 1;
      }
    }
    if (type == 1) {
      var circlesChecked = circleList[index].circlesChecked;
      if (!circlesChecked && count >= 3) {
        return;
      }
      _this.setData({
        ["ordThemeRecommendListAuxiliary.circleList[" + index + "].circlesChecked"]: !circlesChecked
      })
    } else if (type == 2) {
      var circlesChecked = baobeiList[index].circlesChecked;
      if (!circlesChecked && count >= 3) {
        return;
      }
      _this.setData({
        ["ordThemeRecommendListAuxiliary.baobeiList[" + index + "].circlesChecked"]: !circlesChecked
      })
    }
  },

  /**
   * 加载推荐圈子
   */
  loadRecommendedCircles: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.ordTheme.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_getUserRecommendInfoApiUrl, data).then(res => {
          if (res.code == 200) {
            var json = res.result.json;
            _this.setData({
              ["ordThemeRecommendListAuxiliary.circleList"]: json.circleList,
              ["ordThemeRecommendListAuxiliary.baobeiList"]: json.baobeiList
            })
            var ordThemeRecommendList = _this.data.ordThemeRecommendList;
            var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
            var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
            for (var i = 0; i < ordThemeRecommendList.length; i++) {
              var re = ordThemeRecommendList[i];
              var re_recommendId = re.recommendId;
              var re_recommendType = re.recommendType;
              if (re_recommendType == 1) {
                for (var j = 0; j < circleList.length; j++) {
                  if (re_recommendId == circleList[j].id) {
                    _this.setData({
                      ["ordThemeRecommendListAuxiliary.circleList[" + j + "].circlesChecked"]: true
                    })
                  }
                }
              } else if (re_type == 2) {
                for (var j = 0; j < baobeiList.length; j++) {
                  if (re_recommendId == baobeiList[j].id) {
                    _this.setData({
                      ["ordThemeRecommendListAuxiliary.baobeiList[" + j + "].circlesChecked"]: true
                    })
                  }
                }
              }
            }
          }
        })
      })
    }
  },

  /**
   * 语音拒绝授权的提示弹窗关闭
   */
  audioOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.audioOauhRefusedDialogShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },

  /**
   * 语音拒绝授权的提示弹窗确认动作
   */
  audioOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.record"] == true) {
          // 授权成功
          _this.audioOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.audioOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 地址拒绝授权的提示弹窗关闭
   */
  addressOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      ["dataInfoListAuxiliary.addressOauhRefusedDialogShow"]: false,
      ["dataInfoListAuxiliary.isOpenDiaShow"]: false,
    })
  },

  /**
   * 地址拒绝授权的提示弹窗确认动作
   */
  addressOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.userLocation"] == true) {
          // 授权成功
          _this.addressOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.addressOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 校验主题
   */
  checkThemeInfo: function () {
    var _this = this;
    var isRecorderStart = _this.data.dataInfoListAuxiliary.isRecorderStart;
    if (isRecorderStart) {
      util.dialogAlert("录音中~");
      return false;
    }
    var dataInfoList = _this.data.dataInfoList;
    var contentType = _this.data.ordTheme.contentType;
    for (var i = 0; i < dataInfoList.length; i++) {
      var type = String(dataInfoList[i].type);
      switch (type) {
        case "1":
          var value = dataInfoList[i].value;
          if (value.length <= 0) {
            util.dialogAlert("请输入文字~");
            return false;
          }
          break;
        case "5":
          var state = dataInfoList[i].state;
          if (state != 2) {
            util.dialogAlert("请输入链接~");
            return false;
          }
          break;
        case "7":
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入单选的内容~");
            return false;
          }
          var optionFormList = dataInfoList[i].optionFormList;
          for (var j = 0; j < optionFormList.length; j++) {
            var text = optionFormList[j].text;
            if (text.trim().length <= 0) {
              util.dialogAlert("请输入单选的选项内容~");
              return false;
            }
          }
          if (contentType == 3) {
            var answerFormList = dataInfoList[i].answerFormList;
            var isanswer = 0;
            for (var j = 0; j < answerFormList.length; j++) {
              if (isanswer == 0 || isanswer == "") {
                isanswer = answerFormList[j].isanswer;
              }
            }
            if (isanswer == 0 || isanswer == "") {
              util.dialogAlert("请设置单选的答案~");
              return false;
            }
            var score = dataInfoList[i].score;
            if (score <= 0) {
              util.dialogAlert("请设置单选的分值~");
              return false;
            }
          }
          break;
        case "8":
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入多选的内容~");
            return false;
          }
          var optionFormList = dataInfoList[i].optionFormList;
          for (var j = 0; j < optionFormList.length; j++) {
            var text = optionFormList[j].text;
            if (text.trim().length <= 0) {
              util.dialogAlert("请输入多选的选项内容~");
              return false;
            }
          }
          if (contentType == 3) {
            var answerFormList = dataInfoList[i].answerFormList;
            var isanswer = 0;
            for (var j = 0; j < answerFormList.length; j++) {
              if (isanswer == 0 || isanswer == "") {
                isanswer = answerFormList[j].isanswer;
              }
            }
            if (isanswer == 0 || isanswer == "") {
              util.dialogAlert("请设置多选的答案~");
              return false;
            }
            var score = dataInfoList[i].score;
            if (score <= 0) {
              util.dialogAlert("请设置多选的分值~");
              return false;
            }
          }
          break;
        case "9":
          // 判断题
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入判断题目~");
            return false;
          }
          var optionFormList = dataInfoList[i].optionFormList;
          for (var j = 0; j < optionFormList.length; j++) {
            var text = optionFormList[j].text;
            if (text.trim().length <= 0) {
              util.dialogAlert("请输入判断题题目~");
              return false;
            }
          }
          var answerFormList = dataInfoList[i].answerFormList;
          for (var j = 0; j < answerFormList.length; j++) {
            if (answerFormList[j].isanswer != 0 && answerFormList[j].isanswer != 1) {
              util.dialogAlert("请设置判断题答案~");
              return false;
            }
          }
          var score = dataInfoList[i].score;
          if (score <= 0) {
            util.dialogAlert("请设置判断题的分值~");
            return false;
          }
          break;
        case "10":
          // 问答
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入问答题目~");
            return false;
          }
          if (dataInfoList[i].answer == "") {
            util.dialogAlert("请输入问答答案~");
            return false;
          }
          var score = dataInfoList[i].score;
          if (score <= 0) {
            util.dialogAlert("请设置问答题的分值~");
            return false;
          }
          break;
        case "11":
          // 评星
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入评星题目~");
            return false;
          }
          var optionFormList = dataInfoList[i].optionFormList;
          for (var j = 0; j < optionFormList.length; j++) {
            var text = optionFormList[j].text;
            if (text.trim().length <= 0) {
              util.dialogAlert("请输入评星选项~");
              return false;
            }
          }
          break;
        case "12":
          // 填空
          var title = dataInfoList[i].title;
          if (title.trim().length <= 0) {
            util.dialogAlert("请输入填空内容~");
            return false;
          }
          var optionFormList = dataInfoList[i].optionFormList;
          for (var j = 0; j < optionFormList.length; j++) {
            var text = optionFormList[j].text;
            if (text.trim().length <= 0) {
              util.dialogAlert("请输入填空选项~");
              return false;
            }
          }
          if (contentType == 3) {
            var answerFormList = dataInfoList[i].answerFormList;
            var isanswer = 0;
            for (var j = 0; j < answerFormList.length; j++) {
              if (isanswer == 0) {
                isanswer = answerFormList[j].isanswer;
              }
            }
            if (isanswer == 0) {
              util.dialogAlert("请设置填空答案~");
              return false;
            }
          }
          break;
      }
    }
    // 所有的校验都成功了，需要初始化isanswer为0
    for (var i = 0; i < dataInfoList.length; i++) {
      var type = String(dataInfoList[i].type);
      switch (type) {
        case "7":
          if (contentType == 3) {
            var answerFormList = dataInfoList[i].answerFormList;
            for (var j = 0; j < answerFormList.length; j++) {
              if (answerFormList[j].isanswer == "") {
                _this.setData({
                  ["dataInfoList[" + i + "].answerFormList[" + j + "].isanswer"]: 0
                })
              }
            }
          }
          break;
        case "8":
          if (contentType == 3) {
            var answerFormList = dataInfoList[i].answerFormList;
            for (var j = 0; j < answerFormList.length; j++) {
              if (answerFormList[j].isanswer == "") {
                _this.setData({
                  ["dataInfoList[" + i + "].answerFormList[" + j + "].isanswer"]: 0
                })
              }
            }
          }
          break;
        case "9":
          var answerFormList = dataInfoList[i].answerFormList;
          for (var j = 0; j < answerFormList.length; j++) {
            if (answerFormList[j].isanswer == "") {
              _this.setData({
                ["dataInfoList[" + i + "].answerFormList[" + j + "].isanswer"]: 0
              })
            }
          }
          break;
      }
    }
    return true;
  },

  /**
   * 保存主题
   */
  submitThemeInfo: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid == null || openid.length <= 0) {
      util.dialogAlert("请先登录");
      return false;
    }
    // 进行主题信息校验
    if (!_this.checkThemeInfo()) {
      return false;
    }
    wx.showLoading({
      title: '保存中',
    }, 30000)

    // 上传所有文件并提交
    var navigatetype = e.currentTarget.dataset.navigatetype;// 类型：1发布  2预览 3设置
    _this.uploadFileAndSubmit(navigatetype);
  },

  /**
   * 上传所有文件并提交
   */
  uploadFileAndSubmit: function (navigatetype) {
    var _this = this;
    var ordTheme = _this.data.ordTheme;
    var dataInfoList = _this.data.dataInfoList;
    var uploadInfoList = [];// 用来存放所有的上传内容
    var firstImageIp = ordTheme.firstImageIp;
    if (firstImageIp.length <= 0) {
      var uploadInfo = {};
      uploadInfo.type = "1";
      uploadInfo.filePath = ordTheme.firstImageUrl;
      uploadInfoList.push(uploadInfo);
    }
    // 检查图片是否需要上传
    for (var i = 0; i < dataInfoList.length; i++) {
      var type = dataInfoList[i].type;
      if (type == "2") {
        // 图片
        var tempFiles = dataInfoList[i].themeImageList;
        for (var j = 0; j < tempFiles.length; j++) {
          var imageId = tempFiles[j].id;
          if (imageId == null || String(imageId).length <= 0) {
            var uploadInfo = {};
            uploadInfo.type = "2";
            uploadInfo.dataInfoIndex = i;
            uploadInfo.tempFilesIndex = j;
            uploadInfo.filePath = tempFiles[j].path;
            uploadInfoList.push(uploadInfo);
          }
        }
      }
      var id = dataInfoList[i].id;
      if (id == null || String(id).length <= 0) {
        if (type == "3") {
          // 音频
          var uploadInfo = {};
          uploadInfo.type = "3";
          uploadInfo.dataInfoIndex = i;
          uploadInfo.filePath = dataInfoList[i].path;
          uploadInfoList.push(uploadInfo);
        }
        if (type == "4") {
          // 视频
          var uploadInfo = {};
          uploadInfo.type = "4";
          uploadInfo.dataInfoIndex = i;
          uploadInfo.filePath = dataInfoList[i].path;
          uploadInfoList.push(uploadInfo);
        }
        if (type == "5" && dataInfoList[i].type == 2) {
          // 链接
          var uploadInfo = {};
          uploadInfo.type = "5";
          uploadInfo.dataInfoIndex = i;
          uploadInfo.filePath = dataInfoList[i].value;
          uploadInfoList.push(uploadInfo);
        }
      }
    }
    if (uploadInfoList.length > 0) {
      // 开始请求:要先上传
      _this.uploadFileQuery(uploadInfoList, 0, navigatetype);
    } else {
      _this.saveThemeInfo(navigatetype);
    }
  },

  /**
   * 上传所有文件：执行请求
   */
  uploadFileQuery: function (data, queryIndex, navigatetype) {
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "1":
        // 海报
        queryUrl = api.File_doImageUpload;
        break;
      case "2":
        // 图片
        queryUrl = api.File_doImageUpload;
        break;
      case "3":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
      case "4":
        // 视频
        queryUrl = api.File_doVideoUpload;
        break;
      case "5":
        // 链接
        queryUrl = api.File_doOtherUpload;
        break;
    }

    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "10"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "1":
              // 头图
              _this.setData({
                ["ordTheme.firstImageIp"]: ip,
                ["ordTheme.firstImageUrl"]: path,
              })
              break;
            case "2":
              // 图片
              var dataInfoIndex = queryData.dataInfoIndex;// 编辑详情中的下标
              var tempFilesIndex = queryData.tempFilesIndex;// 图片里的下标
              _this.setData({
                ["dataInfoList[" + dataInfoIndex + "].themeImageList[" + tempFilesIndex + "].ip"]: ip,
                ["dataInfoList[" + dataInfoIndex + "].themeImageList[" + tempFilesIndex + "].path"]: path
              })
              break;
            case "3":
              // 音频
              var dataInfoIndex = queryData.dataInfoIndex;// 编辑详情中的下标
              _this.setData({
                ["dataInfoList[" + dataInfoIndex + "].ip"]: ip,
                ["dataInfoList[" + dataInfoIndex + "].path"]: path
              })
              break;
            case "4":
              // 视频
              var dataInfoIndex = queryData.dataInfoIndex;// 编辑详情中的下标
              var ffmpegvideoimagepath = data.result.ffmpegvideoimagepath;
              _this.setData({
                ["dataInfoList[" + dataInfoIndex + "].ip"]: ip,
                ["dataInfoList[" + dataInfoIndex + "].path"]: path,
                ["dataInfoList[" + dataInfoIndex + "].ffmpegvideoimagepath"]: ffmpegvideoimagepath
              })
              if (_this.data.dataInfoList[dataInfoIndex].totalTime <= 0) {
                var width = data.result.width;
                var height = data.result.height;
                var duration = data.result.duration;
                _this.setData({
                  ["dataInfoList[" + dataInfoIndex + "].width"]: width,
                  ["dataInfoList[" + dataInfoIndex + "].height"]: height,
                  ["dataInfoList[" + dataInfoIndex + "].totalTime"]: duration,
                  ["dataInfoList[" + dataInfoIndex + "].totalDate"]: util.digitalFormatTime(duration)
                })
              }
              break;
            case "5":
              // 链接
              var dataInfoIndex = queryData.dataInfoIndex;// 编辑详情中的下标
              _this.setData({
                ["dataInfoList[" + dataInfoIndex + "].ip"]: ip,
                ["dataInfoList[" + dataInfoIndex + "].value"]: path
              })
              break;
          }
        }
      },
      fail(res) {
        // 失败
      },
      complete(res) {
        // 结束：
        if (queryIndex < data.length - 1) {
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex, navigatetype);
        } else {
          // 上传完成，执行save圈子信息
          _this.saveThemeInfo(navigatetype);
        }
      }
    })
  },
  /**
   * save主题信息
   */
  saveThemeInfo: function (navigatetype) {
    var _this = this;
    var ordTheme = _this.data.ordTheme;
    var dataInfoList = _this.data.dataInfoList;
    var ordThemeRecommendList = _this.data.ordThemeRecommendList;
    var o_type = _this.data.o_type;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.access_token = res.access_token;
      data.openid = app.globalData.logininfo.openid;
      data.circleid = _this.data.ordTheme.circleid;// 圈子id
      data.dataInfoList = dataInfoList;
      data.ordThemeRecommendList = ordThemeRecommendList;
      data.o_type = _this.data.o_type;
      data.copyThemeid = ordTheme.id;
      data.settingForm = _this.data.themeSetting;
      data.ordThemeAmount = _this.data.themeAmount;
      data.ordThemeAmountDetailsList = _this.data.themeAmountDetailsList;
      if (o_type == "copy") {
        ordTheme.id = "";
      }
      data.ordTheme = ordTheme;
      util.post(api.Interest_SaveOrUpdateThemeApi, data).then(function (res) {
        wx.hideLoading();
        if (res.code == 200) {
          var themeid = res.result.themeid;
          _this.setData({
            ["ordTheme.id"]: themeid,
            o_type: "update"
          })
          if (navigatetype == 1) {
            // 发布
            wx.redirectTo({
              url: '../themManage/themManage?circleid=' + _this.data.ordTheme.circleid,
            })
          } else if (navigatetype == 2) {
            // 预览
            wx.navigateTo({
              url: '../themeDetails/themeDetails?preview=1&themeid=' + themeid,
            })
          } else if (navigatetype == 3) {
            // 问卷设置
            var contentType = _this.data.ordTheme.contentType;
            wx.navigateTo({
              url: 'punchSetting/punchSetting?circleid=' + _this.data.ordTheme.circleid + '&themeid=' + themeid + '&contentType=' + contentType,
            })
          } else if (navigatetype == 4) {
            // 主题设置
            var contentType = _this.data.ordTheme.contentType;
            wx.navigateTo({
              url: 'themeSet/themeSet?circleid=' + _this.data.ordTheme.circleid +'&themeid=' + themeid + '&contentType=' + contentType,
            })
          }
        } else {
          util.showToast(res.message, "none");
        }
      })
    })
  },

  /**
   * 进入圈子设置页面
   */
  navigateToThemeSet: function () {
    var _this = this;
    var themeid = _this.data.ordTheme.id;
    if (themeid != null && String(themeid).length > 0) {
      wx.navigateTo({
        url: 'themeSet/themeSet?circleid=' + _this.data.ordTheme.circleid +'&themeid=' + themeid + '&contentType=' + _this.data.ordTheme.contentType,
      })
    } else {
      var feeSettingSwitch = _this.data.ordTheme.feeSettingSwitch == null ? 0 : _this.data.ordTheme.feeSettingSwitch;
      var themeNotice = _this.data.ordTheme.themeNotice == null ? "" : _this.data.ordTheme.themeNotice;
      var themeAmount = _this.data.themeAmount;
      var themeAmountDetailsList = _this.data.themeAmountDetailsList;
      wx.navigateTo({
        url: 'themeSet/themeSet?circleid=' + _this.data.ordTheme.circleid +'&themeid=&themeNotice=' + themeNotice + '&feeSettingSwitch=' + feeSettingSwitch + '&themeAmount=' + JSON.stringify(themeAmount) + '&themeAmountDetailsList=' + JSON.stringify(themeAmountDetailsList) + '&contentType=' + _this.data.ordTheme.contentType,
      })
    }
  },
  /**
   * 计算调查统计、测评考试的下标
   */
  setSerial: function () {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    if (contentType > 1) {
      var dataInfoList = _this.data.dataInfoList;
      var serial = 0;
      for (var i = 0; i < dataInfoList.length; i++) {
        var dataInfo = dataInfoList[i];
        if (dataInfo.type >= 7) {
          serial = serial + 1;
          _this.setData({
            ["dataInfoList[" + i + "].serial"]: serial
          })
        }
      }
    }
  },

  /**
   * 题目标题鼠标移入事件
   */
  openTextarea: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var index = e.currentTarget.dataset.index;
    var info = _this.data.dataInfoList;
    info[index].showTextarea = true;
    _this.setData({
      dataInfoList: info,
    })
  },
  /**
   * 题目标题鼠标移出事件
   */
  closeTextarea: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var info = _this.data.dataInfoList;
    info[index].showTextarea = false
    _this.setData({
      dataInfoList: info,
    })
  },
  /**
   * 题目标题输入事件
   */
  inputIssueText: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].title"]: value
    })
  },
  /**
  * 题目选项输入事件
  */
  inputAnswerText: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    var index = e.currentTarget.dataset.index;
    var optionIndex = e.currentTarget.dataset.option;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      _this.setData({
        ["dataInfoList[" + index + "].optionFormList[" + optionIndex + "].text"]: _this.data.dataInfoList[index].optionFormList[optionIndex].text,
      })
      return;
    } else {
      _this.setData({
        ["dataInfoList[" + index + "].optionFormList[" + optionIndex + "].text"]: value,
      })
    }
  },
  /**
  * 题目选项删除事件
  */
  delOption: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var index = e.currentTarget.dataset.index;
    var optionIndex = e.currentTarget.dataset.option;
    var info = _this.data.dataInfoList[index].optionFormList;
    info.splice(optionIndex, 1);
    _this.setData({
      ["dataInfoList[" + index + "].optionFormList"]: info,
    })
  },
  /**
   * 题目选项新增事件
   */
  addOption: function (e) {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var o_type = _this.data.o_type;
    var themeJoinCount = _this.data.themeJoinCount;
    var themeAnswerCount = _this.data.themeAnswerCount;
    if ((contentType == 2 || contentType == 3) && (themeJoinCount > 0 || themeAnswerCount > 0) && o_type != "create" && o_type != "copy") {
      return;
    }
    var index = e.currentTarget.dataset.index;
    _this.addOptionQuery(index);
  },

  /**
   * 题目选项新增：执行
   */
  addOptionQuery: function (index, type) {
    var _this = this;
    var dataInfo = _this.data.dataInfoList[index];
    var optionFormList = dataInfo.optionFormList;
    var optionForm = {};
    optionForm.index = optionFormList.length;
    optionForm.text = "";
    optionFormList.push(optionForm);
    _this.setData({
      ["dataInfoList[" + index + "].optionFormList"]: optionFormList
    })
    var answerFormList = dataInfo.answerFormList;
    if (answerFormList != null && answerFormList.length >= 0) {
      var answerForm = {};
      answerForm.index = answerFormList.length;
      if (type == 9) {
        answerForm.isanswer = "1";
      } else {
        answerForm.isanswer = "";
      }
      answerFormList.push(answerForm);
      _this.setData({
        ["dataInfoList[" + index + "].answerFormList"]: answerFormList,
      })
    }
  },

  /**
   * 答案选中
   */
  answerClick: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionIndex = e.currentTarget.dataset.option;
    var answerFormList = _this.data.dataInfoList[index].answerFormList;
    var isanswer = answerFormList[optionIndex].isanswer;
    var type = _this.data.dataInfoList[index].type;
    if (type == 7) {
      // 单选，需要清除
      for (var i = 0; i < answerFormList.length; i++) {
        _this.setData({
          ["dataInfoList[" + index + "].answerFormList[" + i + "].isanswer"]: 0
        })
      }
    }
    _this.setData({
      ["dataInfoList[" + index + "].answerFormList[" + optionIndex + "].isanswer"]: isanswer == 0 ? 1 : 0
    })
  },

  /**
   * 判断题答案选中
   */
  judgeAnswerClick: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionIndex = e.currentTarget.dataset.option;
    var answer = e.currentTarget.dataset.answer;
    _this.setData({
      ["dataInfoList[" + index + "].answerFormList[" + optionIndex + "].isanswer"]: answer
    })
  },
  /**
   * 选择分数设置
   */
  selectScore: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var arr = _this.data.scoreList;
    var score = arr[value];
    _this.setData({
      ["dataInfoList[" + index + "].score"]: score
    })
  },

  /**
    * 答题类型答案鼠标移入事件
    */
  openAnswerTextarea: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].showAnswerTextarea"]: true,
    })
  },
  /**
   * 答题类型答案鼠标移出事件
   */
  closeAnswerTextarea: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].showAnswerTextarea"]: false,
    })
  },
  /**
   * 答题类型答案输入事件
   */
  inputAnswerTextarea: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].answer"]: value
    })
  },
  /**
   * 打开已选日期面板
   */
  openOccupied: function () {
    var _this = this;
    _this.setData({
      ["ordThemeAuxiliary.showOccupied"]: true
    })
  },
  /**
   * 关闭所有弹窗
   */
  closeMC: function () {
    var _this = this;
    _this.setData({
      ["ordThemeAuxiliary.showOccupied"]: false,
    })
  },
  /**
  * 清空选项
  */
  emptyText: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var contentType = _this.data.ordTheme.contentType;
    if (contentType == 2) {
      for (var i = 0; i < _this.data.dataInfoList[index].optionFormList.length; i++) {
        _this.setData({
          ["dataInfoList[" + index + "].optionFormList[" + i + "].text"]: '',
        })
      }
    }
    if (contentType == 3) {
      for (var i = 0; i < _this.data.dataInfoList[index].optionFormList.length; i++) {
        _this.setData({
          ["dataInfoList[" + index + "].optionFormList[" + i + "].text"]: '',
          ["dataInfoList[" + index + "].answerFormList[" + i + "].isanswer"]: 0,
        })
      }
    }
  },
  /**
   * 进入打卡设置
   */
  gotoPunchSetting: function () {
    var _this = this;
    var contentType = _this.data.ordTheme.contentType;
    var themeSetting = _this.data.themeSetting;
    wx.navigateTo({
      url: 'punchSetting/punchSetting?circleid=' + _this.data.ordTheme.circleid + '&themeid=&contentType=' + contentType + "&themeSetting=" + JSON.stringify(themeSetting),
    })
  },
  
  /**
   * 获取费用信息
   */
  getTicketPrice2: function () {
    var _this = this;
    var circleid = _this.data.ordTheme.circleid;
    var themeid = _this.data.ordTheme.id;
    var type = _this.data.ordTheme.type;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = circleid;
        data.themeid = themeid;
        data.type = type
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeInfoByUpdateApi, data).then(res => {
          if (res.code == 200) {
            _this.getTicketPrice(res.result.ordThemeAmountDetailsList);
          }
        })
      })
    }
  },

  /**
   * 获取费用信息
   */
  getTicketPrice: function (themeAmountDetailsList) {
    var _this = this;
    if (themeAmountDetailsList.length > 0) {
      var minPrice = 0;
      var maxPrice = 0;
      for (var i = 0; i < themeAmountDetailsList.length; i++) {
        var amount = themeAmountDetailsList[i];
        var price = amount.price;
        price = price == null && String(price).length <= 0 && parseInt(price) == 0 ? 0 : price;
        var preferentialSettings = amount.preferentialSettings;
        if (preferentialSettings != null && preferentialSettings != 0){
          var preferentialPrice = amount.preferentialPrice;
          preferentialPrice = preferentialPrice == null && String(preferentialPrice).length <= 0 && parseInt(preferentialPrice) == 0 ? 0 : preferentialPrice;
          var n = preferentialPrice < price ? preferentialPrice : price;
          minPrice = n < minPrice ? n : minPrice;
          maxPrice = n > maxPrice ? n : maxPrice;
        }else{
          minPrice = n < price ? n : price;
          maxPrice = n > price ? n : price;
        }
      }
      var amountDesc = minPrice == maxPrice ? "￥" + minPrice : "￥" + minPrice + "~" + maxPrice;
      if (minPrice == 0 && maxPrice == 0) {
        amountDesc = "免费";
      } else if (themeAmountDetailsList.length == 1) {
        if (maxPrice <= 0){
          amountDesc = "免费";
        }else{
          amountDesc = "￥" + maxPrice;
        }
      }
      _this.setData({
        ["ordThemeAuxiliary.amountDesc"]: amountDesc,
      })
    } else {
      _this.setData({
        ["ordThemeAuxiliary.amountDesc"]: "",
      })
    }
  }
})